package com.qf.myshop.shop_utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.qf.myshop.shop_entity.ResultData;

import java.util.Date;

public class TokenUtil {
    private static final Long tokenExpireTime = 1000 * 60 * 60 * 24L;//  单位毫秒
//    public static final String PRIVATEKEY = "privateKey";
//    public static final String ACCESSTOKEN = "AccessToken";// 公私钥
    private static final String secretKey = "ueor82739sjsd234759jdfijosd289347sdjklfvjsxdr389wrksjdhfjksdyr9234yu89htsdkhfjksdhf83wy4hrsdjkhfsdjkh8i34wyuirfhsdjkfsxmnfbcvm,xcnskdhfriw3eyrikni12y391y238923y4y89dfhisfhsdjknfk23w4y598hfdjkfkjxcfbnisyer93we5rhkdjsfnjks"; // secret

    // 生成token
    public static String createToken(String username){
        // 得到当前时间
        Date now = new Date();
        // 通过hs256算法，以及secretKey得到Algorithm对象
        Algorithm algo = Algorithm.HMAC256(secretKey);
        return JWT.create()
                .withIssuer("shop")
                .withIssuedAt(now)
                .withExpiresAt(new Date(now.getTime() + tokenExpireTime))
                .withClaim("user", username)//保存身份标识
                .sign(algo);
    }



    /**
     * JWT验证
     * @param token 令牌
     * @return userName 用户信息
     */
    public static ResultData verifyJWT(String token){
        String user;
        try {
            Algorithm algorithm = Algorithm.HMAC256(secretKey);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer("shop")
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            user = jwt.getClaim("user").asString();
            return ResultData.createSuccessJsonResult(user);
            // 直接刷新token
//            Date expiresAt = jwt.getExpiresAt();
//            System.out.println("超时时间：" + expiresAt);
//            Date now = new Date();
//            System.out.println("当前时间：" + now);
//            // 如果剩下的时间少于一半，就重新签发令牌（令牌刷新）
//            if (expiresAt.getTime() - now.getTime() < tokenExpireTime / 2){
//                System.out.println("签发新令牌===");
//                String newToken = createToken(username);
//                return ResultData.createFailJsonResult("40000", newToken);
//            }else{
//                return ResultData.createSuccessJsonResult(username);
//            }
        } catch (JWTVerificationException e){
            e.printStackTrace();
        }
        return ResultData.createFailJsonResult("S10002", "用户认证失败，请重新登录");
    }

    public static void main(String[] args) {
        String jwt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJxaWFuZmVuZyIsImV4cCI6MTYwNTYwMzc1NSwidXNlck5hbWUiOiJhZG1pbiIsImlhdCI6MTYwNTYwMTk1NX0.7mgYbJfCSqkauj0Vi7KJba96qHjk7i3CYYj4bCJF5FE";
        System.out.println(verifyJWT(jwt));

//        System.out.println(createToken("admin"));
    }
}